<?php
/**
 * Created by PhpStorm.
 * User: zhouwenping
 * Date: 2017/11/9
 * Time: 下午4:20
 */

namespace app\push\controller;

use \GatewayWorker\Lib\Gateway;
// 使用 Medoo 的命名空间
use Medoo\Medoo;

class Event
{
    public static $rootdir='./src/ws/';
    //声明
   
    /**
     * 进程启动后初始化数据库连接
     */
    public static function onWorkerStart($worker)
    {
        global $db;
      
        $db = new Medoo(config('Meedo_DB'));
        // global $live;
        // $live = new \live();
    }
    
    /**
     * 有消息时
     *
     * @param int   $client_id
     * @param mixed $message
     *
     * @throws Exception
     */
    public static function onMessage($client_id, $message)
    {
        global $db,$json;


        // echo "client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}  client_id:$client_id session:" . json_encode($_SESSION) . " onMessage:" . $message . "\n";
        // 使用数据库实例
        // 客户端传递的是json数据
        $json = json_decode($message, true);
        $exist = isset($json['route']);
        if ($exist) {
            self::myrouter($json['route']);
        } else {
            self::error(2);
        }
        // $tmppath=$rootdir.'testws.php';
        // include $tmppath;
        // Gateway::sendToCurrentClient("hello:赖坤奇大哥哥你真的强，吾为天帝，当镇压世间一切敌:".$info);
    }
    //取值判定
    public static function get($key)
    {
        global $json;
        var_dump($json);
        if (isset($json->$key)) {
            return $json->$key;
        } else {
             self::error(6, $key);
        }


        //return isset($json->$key)?self::$json->$key:self::error(6, $key);
    }
   
    /**
     * 当客户端断开连接时
     *
     * @param integer $client_id 客户端id
     */
    public static function onClose($client_id)
    {
        // debug
        echo "client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}  client_id:$client_id onClose:''\n";
    }

    //{"route":"dx.login","account":"","psw":""}
    public static function myrouter($route)
    {
        //接口调试
        $action =self::trimStr($route);
        // $this->action=$action;
        if ($action!='') {
            $router=str_replace('.', '/', $action);
            $mode=explode('/', $router);
            //接口请求文件存在导入
            $path=self::$rootdir.$router.'.php';
            if (file_exists($path)) {
                //引入分组公用文件
                $tmppath1=dirname($path).'/common.php';
                if (file_exists($tmppath1) and $tmppath!=$tmppath1) {
                    include $tmppath1;
                }
                //引入路由目标文件
                include $path;
            } else {
                //$this->error(5,$path);
                self::error(5);
            }
        } else {
            error(4);
        }
    }
    //过滤
    public static function trimStr($str)
    {
        return preg_match("/^[a-zA-Z0-9\.]*$/", $str)?$str:'';
    }
    //错误返回
    public static function error($n, $v='')
    {
        $error_list=array(
      '{"error":"0","msg":"success"}',
      '{"error":"1","msg":"nothing"}',
      '{"error":"2","msg":"json_format_error"}',
      '{"error":"3","msg":"token_error"}',
      '{"error":"4","msg":"action_empty"}',
      '{"error":"5","msg":"file_not_exists=>%s"}',
      '{"error":"6","msg":"%s_value_empty"}',
      '{"error":"7","msg":"%s_gvalue_empty"}',
      '{"error":"8","msg":"class_notfind"}',
      '{"error":"9","msg":"xxxxxxxxxxx"}',
      '{"error":"10","msg":"xxxxxxxxxxx"}',
      '{"error":"11","msg":"xxxxxxxxxxx"}',
  );

        $rr=($v!='')?sprintf($error_list[$n], $v):$error_list[$n];
        // echo $rr;
        // var_dump('当前的数据'.$rr);
        Gateway::sendToCurrentClient($rr);
        die();
    }

    //检测JSON字符串
    public static function checkJson($jsonstr)
    {
        if ($jsonstr=='') {
            self::error(1);
        }
        $json=json_decode($jsonstr);
        if ($json) {
            return $json;
        } else {
            self::error(2);
        }
    }
}
